package com.xuxin.baby.activity;

import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.entity.LocalMedia;
import com.xuxin.baby.R;
import com.xuxin.baby.base.BaseActivity;
import com.xuxin.baby.base.BaseConstant;
import com.xuxin.baby.bean.BaseBean;
import com.xuxin.baby.bean.UploadFilesBean;
import com.xuxin.baby.contract.ChildGreatRecordContract;
import com.xuxin.baby.contract.ChildSicknessRecordContract;
import com.xuxin.baby.glide.GlideApp;
import com.xuxin.baby.network.Retrofit;
import com.xuxin.baby.photo.PhotoUtils;
import com.xuxin.baby.presenter.ChildGreatRecordPresenter;
import com.xuxin.baby.presenter.ChildSicknessRecordPresenter;
import com.xuxin.baby.utils.ACache;
import com.xuxin.baby.utils.DatePickerUtils;
import com.xuxin.baby.utils.PathUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by xu_xin
 * Created on 2020.08.19 0019
 * 记看病
 */
public class ChildSicknessRecordActivity extends BaseActivity implements ChildGreatRecordContract.View, ChildSicknessRecordContract.View {
    private final ChildGreatRecordContract.Presenter presenter = new ChildGreatRecordPresenter(this);
    private final ChildSicknessRecordContract.Presenter presenter2 = new ChildSicknessRecordPresenter(this);
    RequestOptions options = new RequestOptions().transform(new CenterCrop(), new RoundedCorners(10));
    @BindView(R.id.title_left)
    ImageView title_left;
    @BindView(R.id.title_right)
    ImageView title_right;
    @BindView(R.id.title_name)
    TextView title_name;
    @BindView(R.id.button)
    Button button;
    @BindView(R.id.child_sickness_name)
    EditText child_sickness_name;
    @BindView(R.id.child_sickness_address)
    EditText child_sickness_address;
    @BindView(R.id.child_sickness_time)
    TextView child_sickness_time;
    @BindView(R.id.child_sickness_content)
    EditText child_sickness_content;
    @BindView(R.id.child_sickness_pic1)
    ImageView child_sickness_pic1;
    @BindView(R.id.child_sickness_pic2)
    ImageView child_sickness_pic2;
    @BindView(R.id.child_sickness_pic3)
    ImageView child_sickness_pic3;

    private String tenantId;//租户id
    private String token;//授权token
    private String childId;//宝宝ID

    private String eventTitle;//标题
    private String eventContent;//就诊记录
    private String medicalRecord;//病历名称
    private String address;//就诊地点
    private String eventDate;//就诊日期
    private List<MultipartBody.Part> image_01;//图1
    private List<MultipartBody.Part> image_02;//图2
    private List<MultipartBody.Part> image_03;//图3
    private String pic_01;//图1
    private String pic_02;//图2
    private String pic_03;//图3
    private boolean detail;

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_child_sickness_record);
    }

    @Override
    public void initView() {
        title_name.setText("记看病");
        button.setText("保存");
        child_sickness_time.setText(TimeUtils.getNowString(TimeUtils.getSafeDateFormat("yyyy-MM-dd")));
    }

    @Override
    public void initData() {
        ACache aCache = ACache.get(this);
        tenantId = aCache.getAsString(BaseConstant.tenantId);
        token = aCache.getAsString(BaseConstant.token);
        childId = aCache.getAsString(BaseConstant.childId);

        detail = getIntent().getBooleanExtra("detail", false);
        if (detail) {
            button.setVisibility(View.GONE);
            String medicalRecord = getIntent().getStringExtra("medicalRecord");
            child_sickness_name.setText(medicalRecord);
            String address = getIntent().getStringExtra("address");
            String eventDate = getIntent().getStringExtra("eventDate");
            String eventContent = getIntent().getStringExtra("eventContent");
            String pic_01 = getIntent().getStringExtra("pic_01");
            String pic_02 = getIntent().getStringExtra("pic_02");
            String pic_03 = getIntent().getStringExtra("pic_03");
            child_sickness_address.setText(address);
            child_sickness_time.setText(eventDate);
            child_sickness_content.setText(eventContent);
            if (!StringUtils.isEmpty(pic_01)) {
                String image_01 = Retrofit.image_url + pic_01;
                LogUtils.e("记看病 image_01 = " + image_01);
                GlideApp.with(context).load(image_01).placeholder(R.mipmap.img_load).apply(options).into(child_sickness_pic1);
            }
            if (!StringUtils.isEmpty(pic_02)) {
                String image_02 = Retrofit.image_url + pic_02;
                LogUtils.e("记看病 image_02 = " + image_02);
                GlideApp.with(context).load(image_02).placeholder(R.mipmap.img_load).apply(options).into(child_sickness_pic2);
            }
            if (!StringUtils.isEmpty(pic_03)) {
                String image_03 = Retrofit.image_url + pic_03;
                LogUtils.e("记看病 image_03 = " + image_03);
                GlideApp.with(context).load(image_03).placeholder(R.mipmap.img_load).apply(options).into(child_sickness_pic3);
            }
        }
    }

    @Override
    public void onComplete() {
        dismiss();
    }

    @Override
    @OnClick({R.id.title_left, R.id.child_sickness_time,
            R.id.child_sickness_pic1, R.id.child_sickness_pic2, R.id.child_sickness_pic3,
            R.id.button})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.title_left) {
            finish();
        } else if (id == R.id.child_sickness_time) {
            DatePickerUtils.showDateTime(context, new DatePickerUtils.onListener() {
                @Override
                public void onShow(String time) {
                    child_sickness_time.setText(time);
                }
            });
        } else if (id == R.id.child_sickness_pic1) {
            if (detail) {
                ToastUtils.showShort("图片预览功能尚在完善");
            } else {
                PhotoUtils.openPhoto(context, new PhotoUtils.OnResultListener() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        image_01 = takePhoto(result, child_sickness_pic1);
                    }
                });
            }
        } else if (id == R.id.child_sickness_pic2) {
            if (detail) {
                ToastUtils.showShort("图片预览功能尚在完善");
            } else {
                PhotoUtils.openPhoto(context, new PhotoUtils.OnResultListener() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        image_02 = takePhoto(result, child_sickness_pic2);
                    }
                });
            }

        } else if (id == R.id.child_sickness_pic3) {
            if (detail) {
                ToastUtils.showShort("图片预览功能尚在完善");
            } else {
                PhotoUtils.openPhoto(context, new PhotoUtils.OnResultListener() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        image_03 = takePhoto(result, child_sickness_pic3);
                    }
                });
            }

        } else if (id == R.id.button) {
            medicalRecord = child_sickness_name.getText().toString();
            address = child_sickness_address.getText().toString();
            eventDate = child_sickness_time.getText().toString();
            eventContent = child_sickness_content.getText().toString();
            if (StringUtils.isEmpty(medicalRecord)) {
                ToastUtils.showShort("请输入就诊病例名称");
            } else if (StringUtils.isEmpty(address)) {
                ToastUtils.showShort("请输入就诊地点");
            } else if (StringUtils.isEmpty(eventDate)) {
                ToastUtils.showShort("请输入就诊时间");
            } else if (StringUtils.isEmpty(eventContent)) {
                ToastUtils.showShort("请输入就诊记录");
            } else {
                try {
                    if (null != image_01 && !image_01.isEmpty()) {
                        popup.show();
                        handler.sendEmptyMessage(0);
                    } else if (null != image_02 && !image_02.isEmpty()) {
                        popup.show();
                        handler.sendEmptyMessage(1);
                    } else if (null != image_03 && !image_03.isEmpty()) {
                        popup.show();
                        handler.sendEmptyMessage(2);
                    } else {
                        popup.show();
                        handler.sendEmptyMessage(10);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    dismiss();
                }
            }
        }
    }

    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 0) {
                LogUtils.e("上传第1张");
                presenter2.uploadDiagnosis(tenantId, token, childId,
                        "Edu_EventChild", "pic1", image_01);
            } else if (msg.what == 1) {
                LogUtils.e("上传第2张");
                presenter2.uploadInspection(tenantId, token, childId,
                        "Edu_EventChild", "pic2", image_02);
            } else if (msg.what == 2) {
                LogUtils.e("上传第3张");
                presenter2.uploadOther(tenantId, token, childId,
                        "Edu_EventChild", "pic3", image_03);
            } else if (msg.what == 10) {
                LogUtils.e("记录");
                LogUtils.e("pic_01 = " + pic_01);
                LogUtils.e("pic_02 = " + pic_02);
                LogUtils.e("pic_03 = " + pic_03);
                presenter.record(tenantId,
                        token,
                        childId,
                        "medical",
                        eventTitle,
                        eventContent,
                        medicalRecord,
                        address,
                        eventDate,
                        pic_01,
                        pic_02,
                        pic_03);
            }
            return false;
        }
    });

    @Override
    public void onDiagnosisSuccess(UploadFilesBean uploadFilesBean) {
        if (!StringUtils.isEmpty(uploadFilesBean.getResult())) {
            pic_01 = uploadFilesBean.getResult();
            LogUtils.e("上传第1张成功");
        } else {
            LogUtils.e("上传第1张失败");
        }
        if (null != image_02 && !image_02.isEmpty()) {
            handler.sendEmptyMessage(1);
        } else if (null != image_03 && !image_03.isEmpty()) {
            handler.sendEmptyMessage(2);
        } else {
            handler.sendEmptyMessage(10);
        }
    }

    @Override
    public void onInspectionSuccess(UploadFilesBean uploadFilesBean) {
        if (!StringUtils.isEmpty(uploadFilesBean.getResult())) {
            pic_02 = uploadFilesBean.getResult();
            LogUtils.e("上传第2张成功");
        } else {
            LogUtils.e("上传第2张失败");
        }
        if (null != image_03 && !image_03.isEmpty()) {
            handler.sendEmptyMessage(2);
        } else {
            handler.sendEmptyMessage(10);
        }
    }

    @Override
    public void onOtherSuccess(UploadFilesBean uploadFilesBean) {
        if (!StringUtils.isEmpty(uploadFilesBean.getResult())) {
            pic_03 = uploadFilesBean.getResult();
            LogUtils.e("上传第3张成功");
        } else {
            LogUtils.e("上传第3张失败");
        }
        handler.sendEmptyMessage(10);
    }

    @Override
    public void onSuccess(BaseBean baseBean) {
        setResult(200);
        finish();
    }

    public List<MultipartBody.Part> takePhoto(List<LocalMedia> result, ImageView image) {
        LocalMedia media = result.get(0);
        String path = media.isCompressed() ? media.getCompressPath() : media.getPath();
        GlideApp.with(context).load(path).centerCrop().into(image);
        File file = new File(path);
        RequestBody requestBody = RequestBody.create(file, MediaType.parse("image/jpeg"));
        List<MultipartBody.Part> parts = new ArrayList<>();
        parts.add(MultipartBody.Part.createFormData("files", PathUtils.getImageName(), requestBody));
        return parts;
    }
}